<template>
  <div class="page-order">
    <div class="search-bar">
      <el-form
        :inline="true"
        :model="dataForm"
        @submit.prevent
        @keyup.enter="onGetDataList(page)"
      >
        <el-form-item :label="$t('order.number') + '：'">
          <el-input
            v-model="dataForm.orderNumber"
            :placeholder="$t('order.number')"
            clearable
          />
        </el-form-item>
        <el-form-item :label="$t('order.status') + '：'">
          <el-select
            v-model="status"
            clearable
            :placeholder="$t('order.statusMsg')"
            @change="orderStatus"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('order.theRecipientSName') + '：'">
          <el-input
            v-model="dataForm.receiver"
            :placeholder="$t('order.pleaseEnRecipName')"
            clearable
          />
        </el-form-item>

        <el-form-item :label="$t('shop.contactTel') + '：'">
          <el-input
            v-model="dataForm.mobile"
            :placeholder="$t('order.pleaseEnterNumber')"
            clearable
          />
        </el-form-item>
        <el-form-item :label="$t('order.createTime') + '：'">
          <el-date-picker
            v-model="dateRange"
            type="datetimerange"
            range-separator="-"
            value-format="YYYY-MM-DD HH:mm:ss"
            :start-placeholder="$t('date.start')"
            :end-placeholder="$t('date.end')"
            :default-time="defaultTime"
          />
        </el-form-item>
        <el-form-item>
          <div
            class="default-btn"
            @click="setDateRange(1)"
          >
            {{ $t("date.t") }}
          </div>
        </el-form-item>
        <el-form-item>
          <div
            class="default-btn"
            @click="setDateRange(2)"
          >
            {{ $t( "date.y" ) }}
          </div>
        </el-form-item>
        <el-form-item>
          <div
            class="default-btn"
            @click="setDateRange(3)"
          >
            {{ $t( "date.n" ) }}
          </div>
        </el-form-item>
        <el-form-item>
          <div
            class="default-btn"
            @click="setDateRange(4)"
          >
            {{ $t( "m" ) }}
          </div>
        </el-form-item>

        <el-form-item>
          <div
            class="default-btn primary-btn"
            @click="onSearch(true)"
          >
            {{ $t( "order.query" ) }}
          </div>
          <div
            class="default-btn"
            @click="onClear()"
          >
            {{ $t( "temp.setNull" ) }}
          </div>
          <div
            class="default-btn"
            @click="onGetSoldExcel()"
          >
            {{ $t( "formData.export" ) }}
          </div>
          <div
            v-if="isAuth('order:order:exportunorder')"
            class="default-btn"
            @click="uploadSpu"
          >
            {{ $t("order.BulkShipping") }}
          </div>
        </el-form-item>
      </el-form>
    </div>
    <div class="main">
      <div class="content">
        <!-- 导航 -->
        <div :class="['status-nav','clearfix',showHeadScroll?'status-nav-bottom':'']">
          <ul class="nav-list clearfix">
            <li
              :class="['nav-item', sts === 0 ? 'selected' : '']"
              data-sts="0"
              @click="onSelectNav($event)"
            >
              {{ $t("date.a") }}
            </li>
            <li
              :class="['nav-item', sts === 1 ? 'selected' : '']"
              data-sts="1"
              @click="onSelectNav($event)"
            >
              {{ $t("order.pendingPayment") }}
            </li>
            <li
              :class="['nav-item', sts === 2 ? 'selected' : '']"
              data-sts="2"
              @click="onSelectNav($event)"
            >
              {{ $t("order.toBeShipped") }}
            </li>
            <li
              :class="['nav-item', sts === 3 ? 'selected' : '']"
              data-sts="3"
              @click="onSelectNav($event)"
            >
              {{ $t("order.pendingReceipt") }}
            </li>
            <li
              :class="['nav-item', sts === 5 ? 'selected' : '']"
              data-sts="5"
              @click="onSelectNav($event)"
            >
              {{ $t("order.successfulTransaction") }}
            </li>
            <li
              :class="['nav-item', sts === 6 ? 'selected' : '']"
              data-sts="6"
              @click="onSelectNav($event)"
            >
              {{ $t("order.transactionFailed") }}
            </li>
          </ul>
          <ul class="nav-right" />
        </div>

        <!-- 列标题 -->
        <div :class="['tit', showHeadScroll ? 'fixed-top' : '']">
          <el-row style="width: 100%">
            <el-col :span="7">
              <span class="item product">{{ $t("order.product") }}</span>
            </el-col>
            <el-col
              :span="3"
              class="transaction-price"
            >
              <span class="item">{{ $t("order.transaQuantity") }}</span>
            </el-col>
            <el-col
              :span="3"
              class="column-title"
            >
              <span class="item">{{ $t("order.actualPaymentAmount") }}</span>
            </el-col>
            <el-col
              :span="3"
              class="column-title"
            >
              <span class="item">{{ $t("order.paymentMethod") }}</span>
            </el-col>
            <el-col
              :span="3"
              class="column-title"
            >
              <span class="item">{{ $t("order.buyerConsignee") }}</span>
            </el-col>
            <el-col
              :span="2"
              class="column-title"
            >
              <span class="item">{{ $t("order.orderStatus") }}</span>
            </el-col>
            <el-col
              :span="3"
              class="column-title"
            >
              <span class="item">{{ $t("order.operation") }}</span>
            </el-col>
          </el-row>
        </div>

        <div
          v-for="order in dataList"
          :key="order.orderId"
          class="prod"
        >
          <div class="prod-tit">
            <span>{{ $t("order.number") }}：{{ order.orderNumber }}</span>
            <span>{{ $t("order.createTime") }}：{{ order.createTime }}</span>
          </div>
          <div class="prod-cont">
            <el-row style="width: 100%">
              <el-col
                :span="10"
                style="height: 100%"
              >
                <div class="prod-item">
                  <div
                    v-for="orderItem in order.orderItems"
                    :key="orderItem.orderItemId"
                    class="items name prod-info"
                  >
                    <div class="prod-image">
                      <img
                        v-if="orderItem.pic"
                        alt=""
                        :src="resourcesUrl + orderItem.pic"
                        @error="imgError(orderItem,'pic')"
                      >
                      <img
                        v-else
                        alt=""
                        src="~@/assets/img/def.png"
                      >
                    </div>
                    <div class="prod-name">
                      <div class="prod-con">
                        <div class="pt-prod-info">
                          {{ orderItem.prodName }}
                        </div>
                        <div
                          v-if="order.status > 0 && order.status < 8"
                          class="order-status"
                        >
                          {{
                            [
                              "",
                              $t("order.pendingPayment"),
                              $t("order.toBeShipped"),
                              $t("order.pendingReceipt"),
                              "",
                              $t("order.successfulTransaction"),
                              $t("order.transactionFailed"),
                              $t("group.waitGroup"),
                            ][order.status]
                          }}
                        </div>
                      </div>
                    </div>
                    <div class="prod-price">
                      <span>{{ orderItem.price.toFixed(2) }}</span>
                      <span>{{ orderItem.prodCount }}{{ $t("order.piece") }}</span>
                    </div>
                  </div>
                </div>
              </el-col>
              <el-col
                :span="3"
                style="height: 100%"
              >
                <div class="item">
                  <div>
                    <span class="totalprice">
                      {{
                        (order.actualTotal ? order.actualTotal.toFixed(2) : '')
                          + (order.actualTotal && order.score ? ' + ' : '')
                          + (order.score ? `${order.score + $t("order.score")}` : '')
                      }}
                    </span>
                    <span
                      v-if="order.freightAmount"
                      class="totalprice"
                    >（{{ $t("order.includingFreight") }}：{{
                      $t("order.monetaryUnit")
                    }}{{ order.freightAmount.toFixed(2) }}）</span>
                    <span>{{ $t("order.total") }} {{ order.productNums }}
                      {{ $t("order.piece") }}</span>
                  </div>
                </div>
              </el-col>
              <el-col
                :span="3"
                style="height: 100%"
              >
                <div class="item">
                  <div>
                    <span v-if="order.payType === null || order.status === 1">{{
                      $t("order.unpaid")
                    }}</span>
                    <span v-else>{{
                      [
                        $t("order.pointsPayment"),
                        $t("order.wecProPay"),
                        $t("order.alipayPCPayment"),
                        $t("order.wechatScanCodePayment"),
                        $t("order.wechatH5Payment"),
                        $t("order.weclAccountPay"),
                        $t("order.alipayH5Payment"),
                        $t("order.alipayAPPPayment"),
                        $t("order.wechatAPPPayment"),
                        $t("order.balancePayment"),
                      ][order.payType]
                    }}</span>
                  </div>
                </div>
              </el-col>
              <el-col
                :span="3"
                style="height: 100%"
              >
                <div class="item">
                  <div class="buyer-info">
                    <div class="buyer-name">
                      {{ order.userAddrOrder.receiver }}
                    </div>
                    <div class="buyer-phone">
                      {{ order.userAddrOrder.mobile }}
                    </div>
                  </div>
                </div>
              </el-col>
              <el-col
                :span="2"
                style="height: 100%"
              >
                <div class="item">
                  <span>
                    <span
                      v-if="order.status === 1"
                      type="danger"
                    >{{ $t("order.pendingPayment") }}</span>
                    <span
                      v-else-if="order.status === 2"
                      type="danger"
                    >{{ $t("order.toBeShipped") }}</span>
                    <span
                      v-else-if="order.status === 3"
                      type="danger"
                    >{{ $t("order.pendingReceipt") }}</span>
                    <span
                      v-else-if="order.status === 7"
                      type="danger"
                    >{{ $t("group.waitGroup") }}</span>
                    <span
                      v-else-if="order.status === 5"
                      type="danger"
                    >{{ $t("order.successfulTransaction") }}</span>
                    <span v-else-if="order.status === 6">{{
                      $t("order.transactionFailed")
                    }}</span>
                  </span>
                </div>
              </el-col>
              <el-col
                :span="3"
                style="height: 100%"
              >
                <div class="item">
                  <div class="text-btn-con">
                    <div
                      class="default-btn text-btn"
                      @click="onAddOrUpdate(order.orderNumber)"
                    >
                      {{ $t("seckill.view") }}
                    </div>
                    <div
                      v-if="
                        order.status === 3 && order.isOnlineDelivery === 0
                      "
                      class="default-btn text-btn"
                      @click="reviseLogistics(order.orderNumber)"
                    >
                      {{ $t("order.modifyLogistics") }}
                    </div>
                    <div
                      v-if="
                        order.status === 2 &&
                          (!order.refundStatus || order.refundStatus === 4)
                      "
                      class="default-btn text-btn"
                      @click="onChangeOrder(order)"
                    >
                      {{ $t("order.delivery") }}
                    </div>
                    <div
                      v-if="order.refundStatus"
                      class="default-btn text-btn"
                      @click="refundRoute(order.orderNumber)"
                    >
                      {{ $t("order.refundInformation") }}
                    </div>
                  </div>
                </div>
              </el-col>
            </el-row>
          </div>
        </div>
        <div
          v-if="!dataList.length"
          class="empty"
        >
          {{ $t("order.noData") }}
        </div>
      </div>
    </div>
    <el-pagination
      v-if="dataList.length"
      :current-page="page.currentPage"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="page.pageSize"
      :total="page.total"
      layout="total, sizes, prev, pager, next, jumper"
      @update:page-size="onPageSizeChange"
      @update:current-page="onPageChange"
    />
    <!-- 弹窗, 新增 / 修改 -->
    <AddOrUpdate
      v-if="addOrUpdateVisible"
      ref="addOrUpdateRef"
      @refresh-data-list="onGetDataList"
    />
    <order-delivery-update
      v-if="devyVisible"
      ref="orderDeliveryUpdateRef"
      @refresh-order-amount-update="onGetDataList"
    />
    <!-- 修改物流弹窗 -->
    <el-dialog
      v-model="logVisible"
      :title="$t('order.changeLogisticsInfo')"
      :close-on-click-modal="false"
      width="50%"
      @close="onCloseHandleDialog"
    >
      <!-- 修改 -->
      <div
        v-if="isReviseLog"
        class="revise-log"
      >
        <div class="change-logistics">
          <div class="warning">
            {{ $t("order.ifModifyTheLog") }}
          </div>
          <div class="log-list">
            <div
              v-for="(logItem, index) in logisticsInfo"
              :key="index"
              class="item itemRadio"
            >
              <div class="i-tit">
                <div class="big">
                  {{ $t("order.package") }}{{ index + 1 }}
                </div>
                <div class="text">
                  {{ $t("order.total") }} {{ logItem.productNums }}
                  {{ $t("marketing.item") }}{{ $t("home.product") }}
                </div>
              </div>

              <div class="item-goods">
                <div
                  ref="carouserRef"
                  class="goods-box"
                >
                  <div
                    v-for="(
                      orderItem, i
                    ) in logItem.orderItems"
                    :key="i"
                    class="item"
                  >
                    <div class="img">
                      <prod-pic
                        height="60"
                        width="60"
                        :pic="orderItem.pic"
                      />
                      <div class="number">
                        ×{{ orderItem.prodCount }}
                      </div>
                    </div>
                    <div class="name">
                      {{ orderItem.prodName }}
                    </div>
                  </div>
                </div>
              </div>

              <el-form
                ref="logDataFormRef"
                :model="logDataForm"
                label-width="95px"
                @submit.prevent
                @keyup.enter="onSubmit()"
              >
                <el-form-item
                  :label="$t('order.delType') + '：'"
                  style="text-align: left"
                >
                  <el-radio-group v-model="logItem.tempDeliveryType">
                    <el-radio
                      v-model="radio"
                      :label="1"
                      disabled
                      class="el-radio"
                    >
                      {{ $t("order.needLogistics") }}
                    </el-radio>
                    <el-radio
                      v-model="radio"
                      :label="3"
                      disabled
                      class="el-radio"
                    >
                      {{ $t("order.noNeedRequired") }}
                    </el-radio>
                  </el-radio-group>
                </el-form-item>
                <!--配送方式 线上 线下-->
                <el-form-item
                  v-if="logItem.tempDeliveryType === 1"
                  :label="$t('order.delType') + '：'"
                  style="text-align: left;"
                >
                  <el-radio-group v-model="logItem.deliveryType">
                    <el-radio
                      :label="0"
                      disabled
                    >
                      {{
                        $t("order.onlineDelivery")
                      }}
                    </el-radio>
                    <el-radio
                      :label="1"
                      disabled
                    >
                      {{
                        $t("order.selfDelivery")
                      }}
                    </el-radio>
                  </el-radio-group>
                </el-form-item>
                <div
                  v-if="logItem.deliveryType !== 3 && logItem.deliveryType !== 0"
                  class="info-int"
                >
                  <el-form-item
                    :label="$t('order.courierCompany') + '：'"
                    class="form-item"
                  >
                    <div
                      v-if="logVisible"
                      class="con"
                    >
                      <SelectLazy v-model="logItem.dvyId" />
                    </div>
                  </el-form-item>
                  <el-form-item
                    :label="$t('order.trackingNumber') + '：'"
                    class="form-item"
                  >
                    <el-input
                      v-model="logItem.dvyFlowId"
                      controls-position="right"
                      maxlength="20"
                      :placeholder="$t('order.trackingNumber')"
                      :min="0"
                      :class="['int-frame', errorNum === 1 ? 'errortip' : '']"
                    />
                  </el-form-item>
                </div>
                <div
                  v-if="logItem.deliveryType === 0"
                  class="info-int"
                >
                  <el-form-item
                    :label="$t('order.courierCompany') + '：'"
                    class="form-item"
                    style="text-align: left;"
                  >
                    <div
                      v-if="logVisible"
                      class="con"
                    >
                      {{ deliveryCompanyType?.[logItem.dvyId - 1]?.label }}
                    </div>
                  </el-form-item>
                  <el-form-item
                    :label="$t('order.trackingNumber') + '：'"
                    class="form-item"
                  >
                    {{ logItem.dvyFlowId }}
                  </el-form-item>
                </div>
              </el-form>
            </div>
          </div>
        </div>
      </div>

      <!-- 确认 -->
      <div
        v-if="!isReviseLog"
        class="change-logistics"
      >
        <div class="warning">
          {{ $t("order.ifModifyTheLog") }}
        </div>
        <el-table
          class="log-info-table"
          :data="confirmList"
          :loading="dataListLoading"
        >
          <el-table-column
            property="dvyIdName"
            :label="$t('order.packageName')"
            width="220"
            style="text-align: left"
          />
          <el-table-column
            property="productNums"
            :label="$t('order.amountOfGoods')"
            width="140"
          />
          <el-table-column
            property="delMethod"
            :label="$t('order.deliveryMethod')"
            width="140"
          />
          <el-table-column
            property="dvyName"
            :label="$t('order.logisticsCompany')"
            width="170"
          />
          <el-table-column
            property="dvyFlowId"
            :label="$t('order.trackingNumber')"
          />
        </el-table>
      </div>

      <template #footer>
        <div
          v-if="isReviseLog"
          class="dialog-footer"
        >
          <div
            class="default-btn"
            @click="logVisible = false"
          >
            {{
              $t("crud.filter.cancelBtn")
            }}
          </div>
          <div
            class="default-btn primary-btn"
            @click="onSubmit()"
          >
            {{
              $t("order.save")
            }}
          </div>
        </div>
        <div
          v-if="!isReviseLog"
          class="dialog-footer"
        >
          <div
            class="default-btn"
            @click="backToRevise()"
          >
            {{
              $t("order.backToModify")
            }}
          </div>
          <div
            class="default-btn primary-btn"
            @click="onConfirmRevise()"
          >
            {{
              $t("order.confirmTheChanges")
            }}
          </div>
        </div>
      </template>
    </el-dialog>
    <!-- 批量发货弹窗 -->
    <order-upload
      v-if="uploadVisible"
      ref="spuUploadRef"
      :param="dataForm"
      @refresh-data-list1="onGetWaitingConsignmentExcel"
    />
  </div>
</template>

<script setup>
import AddOrUpdate from './components/add-or-update.vue'
import OrderDeliveryUpdate from './components/delivery-update.vue'
import OrderUpload from './components/upload.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { isAuth } from '@/utils/index'
import { useRoute, useRouter } from 'vue-router'
import moment from 'moment'
const route = useRoute()
const router = useRouter()
const radio = ref('1')

const dataForm = ref({})
const dateRange = ref([])
const defaultTime = ref([
  new Date(2000, 1, 1, 0, 0, 0),
  new Date(2000, 2, 1, 23, 59, 59)
])
const status = ref(null)
const errorNum = ref(0)
// 确认修改弹窗
const isReviseLog = ref(true) // 是否正在修改物流信息
const options = [{
  value: 1,
  label: $t('order.pendingPayment')
},
{
  value: 2,
  label: $t('order.toBeShipped')
},
{
  value: 3,
  label: $t('order.pendingReceipt')
},
{
  value: 5,
  label: $t('order.successfulTransaction')
},
{
  value: 6,
  label: $t('order.transactionFailed')
}]
const deliveryCompanyType = [{
  value: 1,
  label: '顺丰速运'
}, {
  value: 2,
  label: '京东快递'
}, {
  value: 3,
  label: '圆通速递'
}, {
  value: 4,
  label: '韵达快递'
}, {
  value: 5,
  label: '中通快递'
}, {
  value: 6,
  label: '申通快递'
}, {
  value: 7,
  label: '百世快递'
}, {
  value: 8,
  label: 'EMS'
}]
const resourcesUrl = import.meta.env.VITE_APP_RESOURCES_URL
const dataList = ref([])
const page = ref({
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 10 // 每页显示多少条
})
const dataListLoading = ref(false)
const uploadVisible = ref(false)
let oldPar = {}

onActivated(() => {
  // 携带参数查询
  const query = route.query
  if (Object.keys(query).length > 0) {
    onGetDataList(page.value, query)
    query?.orderNumber && onAddOrUpdate(query.orderNumber)
  }
})
onMounted(() => {
  // 携带参数查询
  onGetDataList(page.value, route.query)
  route.query?.orderNumber && onAddOrUpdate(route.query?.orderNumber)
  // 请求物流公司
  onGetLogisticsList()

  // 监听页面滚动
  window.addEventListener('scroll', scrollToTop)
})

/**
 * 弹窗关闭事件
 */
const onCloseHandleDialog = () => {
  isReviseLog.value = true
}
/**
 * 页面滚动事件
 */
const showHeadScroll = ref(false)
const scrollToTop = () => {
  const scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
  showHeadScroll.value = scrollTop > 400
}
/**
  * 获取包裹物流信息
  */
const logVisible = ref(false)
const logisticsInfo = ref([]) // 包裹列表
const confirmList = ref([])

const reviseLogistics = (orderNumber) => {
  const packageName = $t('order.package')
  logVisible.value = !logVisible.value
  http({
    url: http.adornUrl('/order/delivery/getOrderDeliveries/' + orderNumber),
    method: 'put'
  }).then(({ data }) => {
    logisticsInfo.value = data
    logisticsInfo.value.forEach((el, index) => {
      el.tempDeliveryType = el.deliveryType === 1 || el.deliveryType === 0 ? 1 : el.deliveryType
      el.newDvyFlowId = el.dvyFlowId
      el.newDvyId = el.dvyId
      el.dvyIdName = packageName + Number(index + 1)
      // 修改弹窗
      confirmList.value = [] // 清空确认列表
    })
  })
  errorNum.value = 0
}
/**
 * 获取数据列表
 */
let tempSearchForm = null // 保存上次点击查询的请求条件
const sts = ref(0)
const onGetDataList = (pageParam, params, type = 0, newData = false) => {
  let par = Object.assign(
    {
      orderNumber: dataForm.value.orderNumber,
      shopName: dataForm.value.shopName,
      receiver: dataForm.value.receiver,
      mobile: dataForm.value.mobile,
      status: status.value,
      refundStatus: dataForm.value.refundStatus,
      startTime: dateRange.value === null ? null : dateRange.value[0], // 开始时间
      endTime: dateRange.value === null ? null : dateRange.value[1] // 结束时间
    },
    params
  )
  if (type === 0) {
    oldPar = par
  } else {
    par = oldPar
  }
  if (newData || !tempSearchForm) {
    tempSearchForm = JSON.parse(JSON.stringify(par))
  } else {
    tempSearchForm.status = status.value
  }
  page.value = (page.value === undefined ? page.value : page.value)
  dataListLoading.value = true
  http({
    url: http.adornUrl('/score/order/page'),
    method: 'get',
    params: http.adornParams(
      Object.assign(
        {
          current: pageParam == null ? page.value.currentPage : pageParam.currentPage,
          size: pageParam == null ? page.value.pageSize : pageParam.pageSize
        },
        tempSearchForm
      ), false
    )
  }).then(({ data }) => {
    dataList.value = data.records
    onHandleDataList()
    page.value.total = data.total
    sts.value = !status.value ? 0 : status.value
    dataListLoading.value = false
  })
}

const onHandleDataList = () => {
  dataList.value.forEach(order => {
    let isOnlineDelivery = 1
    for (let i = 0; i < order.orderItems.length; i++) {
      if (order.orderItems[i].dvyType === 1) {
        isOnlineDelivery = 0
        break
      }
    }
    order.isOnlineDelivery = isOnlineDelivery
  })
}
// 每页数
const onPageSizeChange = (val) => {
  page.value.pageSize = val
  page.value.currentPage = 1
  onGetDataList(page.value, {}, 1)
}
// 当前页
const onPageChange = (val) => {
  page.value.currentPage = val
  onGetDataList(page.value, {}, 1)
}

/**
 * 导航选择状态
 */
const onSelectNav = (e) => {
  const isSts = e.currentTarget.dataset.sts
  sts.value = parseInt(isSts)
  status.value = sts.value === 0 ? null : parseInt(isSts)
  onGetDataList(page.value)
}
// 多选
const orderStatus = (val) => {
  status.value = val
}
/**
 * 根据选项设置时间
 * 1:今天 2:昨天 3: 近七天 4:近30天 5:近60天
 */
const setDateRange = (val) => {
  let startDay = null
  let endDay = null
  if (val === 1) {
    startDay = 0
    endDay = 0
  } else if (val === 2) {
    startDay = -1
    endDay = -1
  } else if (val === 3) {
    startDay = -6
    endDay = 0
  } else if (val === 4) {
    startDay = -29
    endDay = 0
  } else {
    return
  }
  // 开始时间
  const startTime = moment().add(startDay, 'days').startOf('days').format('LL')
  // 结束时间
  const endTime = moment().add(endDay, 'days').endOf('days').format('LL')
  dateRange.value = [startTime, endTime]
}
// 新增 / 修改
const addOrUpdateVisible = ref(false)
const addOrUpdateRef = ref(null)
const onAddOrUpdate = (val) => {
  addOrUpdateVisible.value = true
  nextTick(() => {
    addOrUpdateRef.value?.init(val)
  })
}
// 退款路由跳转
const refundRoute = (val) => {
  router.push({
    path: '/order-orderRefund',
    query: { orderNumber: val }
  })
}
// 清空按钮
const onClear = () => {
  dataForm.value = {}
  dateRange.value = []
  status.value = null
}
// 搜索查询
const onSearch = (newData = false) => {
  page.value.currentPage = 1
  onGetDataList(page.value, null, 0, newData)
}
/**
   * 发货
   */
const devyVisible = ref(false)
const orderDeliveryUpdateRef = ref(null)
const onChangeOrder = (order) => {
  devyVisible.value = true
  nextTick(() => {
    orderDeliveryUpdateRef.value?.init(order)
  })
}
/**
 * 请求物流公司列表
 */
const logDataForm = ref({
  dvyId: '', // 当前物流公司id
  dvyFlowId: '', // 物流单号
  dvyNames: [] // 物流公司列表
})
const onGetLogisticsList = () => {
  http({
    url: http.adornUrl('/admin/delivery/list'),
    method: 'get',
    params: http.adornParams()
  }).then(({ data }) => {
    logDataForm.value.dvyNames = data
  })
}
/**
   * 点击保存
   */
const onSubmit = () => {
  let flag = true
  logisticsInfo.value.forEach((el) => {
    if (el.deliveryType === 3 || el.deliveryType === 0) {
      return
    }
    if (!flag) {
      return false
    }
    const reg = /^[a-zA-Z0-9]{4,30}$/
    if (el.dvyFlowId.length === 0) {
      ElMessage({
        message: $t('order.logEmpty'),
        type: 'warning'
      })
      flag = false
      errorNum.value = 1
      confirmList.value = []
    } else if (!reg.test(el.dvyFlowId)) {
      ElMessage({
        message: $t('order.checkDvyId'),
        type: 'warning'
      })
      flag = false
      errorNum.value = 1
      confirmList.value = []
    } else {
      errorNum.value = 0
      const isConfirmList = confirmList.value
      if ((el.newDvyFlowId.length !== 0 && el.newDvyFlowId !== el.dvyFlowId) || (el.newDvyId !== el.dvyId)) {
        isConfirmList.push(el)
        isConfirmList.forEach((el) => {
          el.delMethod = $t('order.logistics')
          logDataForm.value.dvyNames.forEach((dvyName) => {
            if (el.dvyId === dvyName.dvyId) {
              el.dvyName = dvyName.dvyName
            }
          })
        })
        confirmList.value = isConfirmList
      }
    }
  })
  if (errorNum.value === 1) {
    return
  } else if (confirmList.value.length === 0) {
    ElMessage({
      message: $t('order.noLogIsChanged'),
      type: 'warning'
    })
    flag = false
  }
  if (flag) {
    isReviseLog.value = false // 修改弹窗
  }
}
/**
 * 确认修改物流信息
 */
const onConfirmRevise = () => {
  http({
    url: http.adornUrl('/order/delivery/updateOrderDeliveries'),
    method: 'put',
    data: http.adornData({
      deliveryOrders: confirmList.value
    }),
    params: http.adornParams()
  }).then(() => {
    ElMessage({
      message: $t('publics.operation'),
      type: 'success'
    })
    isReviseLog.value = true
    logVisible.value = false
  })
}
/**
 * 返回修改（物流信息）
 */
const backToRevise = () => {
  isReviseLog.value = true
  // 修改弹窗
  confirmList.value = [] // 清空确认列表
}
const onGetSoldExcel = () => {
  if (!dateRange.value || dateRange.value.length < 2) {
    ElMessage.error($t('order.pleExpOrderFirst'))
    return
  }
  ElMessageBox.confirm($t('order.exportReport'), $t('remindPop.remind'), {
    confirmButtonText: $t('remindPop.confirm'),
    cancelButtonText: $t('remindPop.cancel'),
    type: 'warning'
  }).then(() => {
    http({
      url: http.adornUrl('/score/order/soldExcel'),
      method: 'get',
      params: http.adornParams({
        orderNumber: dataForm.value.orderNumber,
        shopName: dataForm.value.shopName,
        receiver: dataForm.value.receiver,
        mobile: dataForm.value.mobile,
        status: status.value,
        refundStatus: dataForm.value.refundStatus,
        startTime: dateRange.value === null ? null : dateRange.value[0], // 开始时间
        endTime: dateRange.value === null ? null : dateRange.value[1] // 结束时间
      }),
      responseType: 'blob' // 解决文件下载乱码问题
    }).then(({ data }) => {
      const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' })
      const fileName = $t('order.orderInfCollationXls')
      const elink = document.createElement('a')
      if ('download' in elink) { // 非IE下载
        elink.download = fileName
        elink.style.display = 'none'
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(elink.href) // 释放URL 对象
        document.body.removeChild(elink)
      } else { // IE10+下载
        navigator.msSaveBlob(blob, fileName)
      }
    })
  })
}
const onGetWaitingConsignmentExcel = () => {
  onGetDataList(page.value)
}
const spuUploadRef = ref(null)
const uploadSpu = () => {
  dataForm.value.startTime = dateRange.value === null ? null : dateRange.value[0]
  dataForm.value.endTime = dateRange.value === null ? null : dateRange.value[1]
  uploadVisible.value = true
  nextTick(() => {
    spuUploadRef.value?.init()
  })
}
onUnmounted(() => {
  // 页面销毁时移除监听
  window.removeEventListener('scroll', scrollToTop)
})

</script>
<style scoped lang="scss">
.page-order {
  .clearfix:after {
  /*伪元素是行内元素 正常浏览器清除浮动方法*/
  content: "";
  display: block;
  height: 0;
  clear: both;
  visibility: hidden;
}
  .main {
    .status-nav {
      position: relative;
      display: block;
      width: 100%;
      margin-top: 15px;
      margin-bottom: 15px;
      height: 40px;
      line-height: 40px;
      border-bottom: 1px solid #ddd;
      ul,
      li {
        list-style: none;
        padding: 0;
        margin: 0;
      }
      .nav-item {
        float: left;
        height: 40px;
        line-height: 40px;
        background: #f8f8f9;
        border: 1px solid #ddd;
        padding: 0 20px;
        margin: 0 -1px -1px 0;
        cursor: pointer;
      }

      .selected {
        background: #fff;
        border-bottom: 1px solid #fff;
      }
    }
    .status-nav-bottom{
      margin-bottom: 72px;
    }
    .tit {
      margin-bottom: 15px;
      background: #f8f8f9;
      z-index: 11;
    }
    .fixed-top {
      position: fixed;
      width: 84%;
      top: 90px;
      left: 267px;
    }
    .column-title {
      text-align: center;
    }
    .transaction-price {
      text-align: right;
    }
  }
  .prod {
    margin-bottom: 15px;
  }
  .tit {
    display: flex;
    height: 45px;
    align-items: center;
  }
  .tit .item {
    padding: 0 10px;
    width: 10%;
    text-align: center;
  }
  .tit .product {
    width: 25%;
  }
  .prod-tit {
    padding: 10px;
    background: #f8f8f9;
    border-left: 1px solid #dddee1;
    border-top: 1px solid #dddee1;
    border-right: 1px solid #dddee1;
  }
  .prod-tit span {
    margin-right: 15px;
  }
  .prod-cont {
    display: flex;
    border-top: 1px solid #dddee1;
    border-bottom: 1px solid #dddee1;
    border-left: 1px solid #dddee1;
    color: #495060;
  }
  .prod-cont .item {
    display: flex;
    display: -webkit-flex;
    align-items: center;
    justify-content: center;
    padding: 10px;
    border-right: 1px solid #dddee1;
    text-align: center;
    height: 100%;
  }
  .prod-cont .item span {
    display: block;
  }
  .prod-cont .prod-item {
    display: flex;
    flex-direction: column;
    border-right: 1px solid #dddee1;
    height: 100%;
  }
  .prod-name {
    width: 55%;
    text-align: left;
    vertical-align: middle;
  }
  .prod-con {
    display: block;
    padding: 0 !important;
  }
  .prod-con .pt-prod-info {
    text-overflow: ellipsis;
    -o-text-overflow: ellipsis;
    word-break: break-word;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }
  .prod-price {
    position: absolute;
    right: 10px;
    text-align: center;
  }
  .prod-price span {
    display: block;
  }
  .prod-price span:first-child {
    margin-bottom: 10px;
  }
  .prod-name .prod-info {
    display: block;
    color: #80848f;
    margin-top: 30px;
  }
  .buyer-info {
    display: block;
    width: 100%;
  }
  .buyer-name {
    margin-bottom: 10px;
  }
  .order-status {
    display: inline-block;
    margin-top: 15px;
    padding: 2px 4px;
    border: 1px solid #e43130;
    border-radius: 2px;
    color: #e43130;
    margin-right: 5px;
  }
  .prod-cont .items.name {
    display: flex;
    align-items: center;
    position: relative;
    padding: 10px;
    height: 100%;
    border-bottom: 1px solid #dddee1;
  }
  .prod-cont .items.name:last-child {
    border-bottom: none;
  }
  .prod-image {
    margin-right: 20px;
    width: 80px;
    height: 80px;
  }
  .prod-image img {
    width: 100%;
    height: 100%;
  }
  .itemRa span {
    display: inline-block;
  }
  .totalprice {
    margin-bottom: 10px;
  }
  .item .totalprice {
    color: #c00;
  }
  :deep(.el-button) + :deep(.el-button) {
  margin-left: 0 !important;
  display: block;
}
div :deep(.el-radio__input){
  display: inline-block !important;
}
div :deep(.el-radio__input.is-disabled + span.el-radio__label) {
  display: inline-block;
  vertical-align: middle;
}

.change-logistics .warning {
    padding: 10px;
    border: 1px solid #f1924e;
    background: #fff5ed;
  }

  .change-logistics .item {
    padding-bottom: 20px;
  }
  .revise-log .change-logistics .info-int {
    display: flex;
  }

  .change-logistics .item .i-tit {
    display: flex;
    align-items: center;
  }

  .change-logistics .item .i-tit .big {
    font-weight: 600;
    margin-right: 15px;
  }
.empty {
  display: block;
  height: 200px;
  line-height: 200px;
  text-align: center;
  color: #aaa;
}
.buyer-name {
  word-break: break-word;
}
@media (max-width:1660px) {
  .fixed-top {
    width: 79.5% !important;
  }
}
@media (max-width:1360px) {
  .fixed-top {
    width: 75.5% !important;
  }
}
div :deep(.el-step__description) {
    min-width: 186px;
}
}
.revise-log .change-logistics .item-goods {
  position: relative;
  width: 100%;
  height: 110px;
  overflow-x: auto;
  .goods-box {
    position: absolute;
    left: 0;
    display: flex;
    margin-top: 0;
    -webkit-transition: all 0.3s;
    -moz-transition: all 0.3s;
    transition: all 0.3s;
    .item {
      margin-right: 10px;
      font-size: 12px;
      cursor: pointer;
      .img {
        width: 60px;
        height: 60px;
        font-size: 0;
        margin-bottom: 4px;
        margin-top: 4px;
        position: relative;
        .number {
          position: absolute;
          bottom: 0;
          right: 0;
          background: rgba(0, 0, 0, 0.3);
          color: #fff;
          border-radius: 6px 0 6px 0;
          font-size: 12px;
          height: 16px;
          line-height: 16px;
          padding: 0 5px;
        }
      }
      .name {
        width: 60px;
        height: 16px;
        line-height: 16px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        color: #999;
      }
    }
    .item:last-child {
      margin: 0;
    }
  }
}
</style>
